package emas.server.core;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import emas.shared.Location;
import emas.shared.SQLConstants;


public class LocationManager {
	private ArrayList<Location> locations = new ArrayList<Location>();
	private static LocationManager instance = new LocationManager();

	private LocationManager() {

	}
	
	public synchronized ArrayList<Location> getLocations() {
		return locations;
	}

	
	public void addLocation(Location location) {
		MySQLConnectionManager connectionManager = MySQLConnectionManager.getInstance();
		GeoCoderManager geoCoderManager = GeoCoderManager.getInstance();
		geoCoderManager.getLatLngfromAddressForLocation(location);
		connectionManager.insertLocation(location);
		updateLocations();
	}

	public void removeLocation(Location location) {
		MySQLConnectionManager connectionManager = MySQLConnectionManager.getInstance();
		connectionManager.removeLocation(SQLConstants.location_id, Integer.toString(location.getId()));
		updateLocations();
	}
	
	public void updateLocation(Location location){
		MySQLConnectionManager connectionManager = MySQLConnectionManager.getInstance();
		connectionManager.updateLocation(SQLConstants.location_id, Integer.toString(location.getId()), location);
		updateLocations();
	}

	public synchronized void updateLocations() {
		clearLocations();
		MySQLConnectionManager manager = MySQLConnectionManager.getInstance();
		ResultSet locationSet = manager.selectQuery("SELECT * FROM "+SQLConstants.location_table);

		try {
			if(locationSet != null){
				while (locationSet.next()) {
					Location loc = new Location(
							locationSet.getInt(SQLConstants.location_id),
							locationSet.getString(SQLConstants.location_name),
							locationSet.getString(SQLConstants.location_ip),
							locationSet.getString(SQLConstants.location_address),
							locationSet.getString(SQLConstants.location_comment),
							locationSet.getString(SQLConstants.location_password),
							locationSet.getDouble(SQLConstants.location_lat),
							locationSet.getDouble(SQLConstants.location_lng));
					locations.add(loc);
	
				}
//				WeatherDataManager.getInstance().addWeatherToLocations();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		TemperaturDataManager.getInstance().updateData();
	}

	private void clearLocations() {
		locations.clear();
	}

	public static LocationManager getInstance() {
		if (instance == null) {
			instance = new LocationManager();
		}
		return instance;
	}

}
